package cn.wolfcode.crm.service.imp;


import cn.wolfcode.crm.domain.*;
import cn.wolfcode.crm.mapper.SaleorderMapper;
import cn.wolfcode.crm.mapper.SaleorderitemMapper;
import cn.wolfcode.crm.qo.PageResult;
import cn.wolfcode.crm.qo.QueryObject;
import cn.wolfcode.crm.service.IMemberInfoService;
import cn.wolfcode.crm.service.ISaleorderService;
import cn.wolfcode.crm.service.IStockOutcomeBillService;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Service
public class SaleorderServiceImpl implements ISaleorderService {
    @Autowired
    private SaleorderMapper saleorderMapper;

    @Autowired
    private SaleorderitemMapper saleorderitemMapper;


    @Autowired
    private IMemberInfoService memberInfoService;



    @Autowired
    private IStockOutcomeBillService stockOutcomeBillService;


    @Override
    public void deleteByPrimaryKey(Long id) {
        if (id != null) {

        saleorderMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public void saveOrUpdate(Saleorder record) {
        if (record.getId() != null) {
            update(record);
        }else {
            insert(record);
        }
    }

    private void insert(Saleorder record) {
        // 判断必须有一条数据
        if (record.getItems().size() == 0) {
            throw new RuntimeException("至少购买一个商品!");
        }

        // 设置销售员,销售时间
        Employee user = UserContext.getCurrentUser();
        record.setSaleName(user.getUsername());
        record.setSaleDate(new Date());

        // 重新计算数量和总价
        BigDecimal totalNumber = BigDecimal.ZERO;
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (Saleorderitem item : record.getItems()) {
            // 重新计算总价
            BigDecimal amount = item.getNumber().multiply(item.getSalePrice()).setScale(2,RoundingMode.HALF_UP);
            item.setAmount(amount);
            // 累加总量
            totalNumber = totalNumber.add(item.getNumber());
            totalAmount = totalAmount.add(amount);
        }
        // 重新设置总量
        record.setTotalNumber(totalNumber);
        record.setTotalAmount(totalAmount);

        // 保存到数据库
        saleorderMapper.insert(record);
        // 在保存明细
        for (Saleorderitem item : record.getItems()) {
            item.setBillId(record.getId());
            saleorderitemMapper.insert(item);
        }


        // 扣除指定会员卡的钱
        if (Optional.ofNullable(record.getCardId()).isPresent() && record.getStatus() == Saleorder.AUDITED) {
            memberInfoService.vipConsume(record.getCardId(), totalAmount, record.getId());

            // 保存到出库单
            insertIntoStockOutcomeBill(record);
        }
    }


    private void update(Saleorder record) {
    }


    @Override
    public Saleorder selectByPrimaryKey(Long id) {

        Saleorder dept = saleorderMapper.selectByPrimaryKey(id);
        return dept;

    }

    @Override
    public List<Saleorder> selectAll() {
        List<Saleorder> depts = saleorderMapper.selectAll();
        return depts;
    }


    @Override
    public PageResult query(QueryObject qo) {
        int rows = saleorderMapper.query4count(qo);
        if (rows==0) {
            return PageResult.EMPTY_RESULT;
        }
        PageResult result =  new PageResult(rows,saleorderMapper.query4list(qo));
        return result;
    }

    @Override
    public void audit(Long id) {
        Saleorder saleorder = saleorderMapper.selectByPrimaryKey(id);
        if (Optional.ofNullable(saleorder).isPresent() && saleorder.getStatus() == Saleorder.NO_AUDITED) {
            // 未审核
            saleorder.setStatus(Saleorder.AUDITED);
            saleorderMapper.audit(saleorder);

            // 扣钱
            memberInfoService.vipConsume(saleorder.getCardId(), saleorder.getTotalAmount(), saleorder.getId());

            // 保存到出库单
            insertIntoStockOutcomeBill(saleorder);
        }
    }

    @Override
    public List<HashMap<String, Object>> selectSaleAnalyzeList() {
        return saleorderMapper.selectSaleAnalyzeList();
    }

    @Override
    public List<HashMap<String, Object>> selectMemberPurchaseRecord(QueryObject qo) {
        return saleorderitemMapper.selectByMemberId(qo);
    }


    // 保存到出库单
    private void insertIntoStockOutcomeBill(Saleorder record) {
        StockOutComeBill bill = new StockOutComeBill();
        bill.setSn(record.getOrderNumber());
        bill.setVdate(record.getSaleDate());
        bill.setStatus(StockOutComeBill.AUDITED);
        bill.setTotalAmount(record.getTotalAmount());
        bill.setTotalNumber(record.getTotalNumber());
        bill.setInputTime(new Date());
        bill.setInputUser(UserContext.getCurrentUser());
        bill.setAuditTime(new Date());
        bill.setAuditor(UserContext.getCurrentUser());
        bill.setOutType(1);// 销售类型
        for (Saleorderitem saleorderitem : record.getItems()) {
            StockOutcomeBillItem item = new StockOutcomeBillItem();
            item.setSalePrice(saleorderitem.getSalePrice());
            item.setNumber(saleorderitem.getNumber());
            item.setAmount(saleorderitem.getAmount());
            item.setRemark(saleorderitem.getRemark());
            item.setProduct(saleorderitem.getProduct());
            bill.getItems().add(item);
        }
        stockOutcomeBillService.saveOrUpdate(bill);
    }
}
